//  this library.
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/login/login_type_enum.dart';
import 'package:hktk_app/ienum/login/sms_code_type.dart';
import 'package:hktk_app/model/login/change_model.dart';
import 'package:hktk_app/model/login/config_model.dart';
import 'package:hktk_app/model/login/token_model.dart';
import 'package:hktk_app/model/login/user_info_model.dart';
import 'package:hktk_app/util/dao_util.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/device_util.dart';
import 'package:hktk_app/util/encrypt_util.dart';
import 'package:hktk_app/util/my_util.dart' show saveTokenFun, saveUserInfoFun;
// import 'package:hktk_app/util/navigator_util.dart';

/// 后端登录接口
class LoginDao {
  /// 保存登录token
  static const String _saveTokenKey = "save_hktk_token";

  /// 保存用户信息方法
  static const String _saveUserKey = "save_user_key";

  /// 内容详情
  static const String _appConfig = "app_config";
  static late  BuildContext? _context;

  static String getAppConfig() {
    return _appConfig;
  }
  static String getSaveTokenKey() {
    return _saveTokenKey;
  }
  static String getSaveUserKey() {
    return _saveUserKey;
  }

  /// 通过code获取详情
  static Future<ConfigModel?> config() async {

    String url = "/user/sys/group/config";
    // 发送请求
    var data = await httpGET(url: url, tips: "通过code获取详情");
    if (data != null) {
      return ConfigModel.fromJson(data);
    }
    return null;
  }

  /// 通过code获取详情
  static Future<Map<String, dynamic>?> configDetail(
      {required String key}) async {
    String url = "/user/sys/config/detail/$key";
    // 发送请求
    var data = await httpGET(url: url, tips: "通过code获取详情2");
    if (data != null) {
      String str = data.toString().replaceAll(",", ":");
      return json.decode(str);
    }
    return null;
  }

  /// 登录接口。
  // deviceType：设备类型。
  // deviceId：设备id，移动端时必传。
  // deviceName：设备名，移动端必传。
  // userAccount：帐户或手机号。
  // credential：非快捷登录时必传密码。
  // type：登录类型。
  // code：验证码登录时必传。
  // groupId：机构ID。
  // token：易盾token。
  // accessToken：运营商授权码。
  static Future<bool> login({
    String? deviceName,
    required String userAccount,
    String? credential,
    required LoginTypeEnum type,
    String? code,
    String? token,
    String? accessToken,
  }) async {
    String deviceType;
    String deviceId;
    try {
      // 设备类型
      deviceType = DeviceUtil.getDeviceType();
      // 设备唯一标识
      deviceId = await DeviceUtil.getDeviceId();
    } catch (e) {

      throw DaoException(
        msg: "获取信息错误，请重试",
        code: -1,
      );
    }
    // 封装条件
    Map<String, dynamic> params = {
      "deviceType": deviceType,
      "deviceId": deviceId,
      "deviceName": deviceName ?? "",
      "userAccount": userAccount,
      "credential": credential ?? "",
      "type": type.name,
      "code": code ?? "",
      "groupId": getGroupId(),
      "token": token ?? "",
      "accessToken": accessToken ?? "",
      "userType": "member",
    };


    String url = "/user/login";
    // 发送请求
    var data = await httpPOST(url: url, params: params, tips: "登录接口");
    if (data != null) {
      // 成功，保存token到本地
      TokenModel tokenModel = TokenModel.fromJson(data);
      // log("tokenModel ===> ${tokenModel.toJson()}");
      saveTokenFun(tokenModel.token!);
      UserInfoModel model = UserInfoModel(
        id: tokenModel.id!,
        name: tokenModel.name!,
        mobile: tokenModel.mobile ?? "",
        header: tokenModel.header ?? "",
      );
      saveUserInfoFun(model);
      dataUtilComm.dataModel.visitorsType = false;
      return true;
    }
    return false;
  }

  /// 发送验证码接口
  static Future<bool> phoneCode({
    required String phone,
    SmsCodeType smsCodeType = SmsCodeType.login,
  }) async {
    // 获取时间戳
    var epoch = DateTime.now().millisecondsSinceEpoch;
    // 根据时间戳 计算key值
    String sign = EncryptUtil.getMd5Sign(time: epoch.toString(), phone: phone);

    String url =
        "/user/cu/sms/phone-code/$phone?sign=$sign&timestamp=${epoch.toString()}&imageCheck=false&smsCodeType=${smsCodeType.name}";
    // 发送请求
    await httpGET(url: url, tips: "获取手机验证码");
    return true;
  }



  // userAccount：手机号，
  // code：验证码，
  // credential：密码，
  // change：true:重置密码|false:忘记密码，
  /// 重置密码
  static Future<ChangeModel> changePass({
    required String userAccount,
    required String code,
    required String credential,
    required bool change,
  }) async {
    String url = change ? "/user/change-pass" : '/user/forget-pass';
    Map<String, dynamic> params = {
      "userAccount": userAccount,
      "code": code,
      "credential": credential,
    };
    // 发送请求
    String tips = change ? "重置密码" : "忘记密码";
    var data = await httpPOST(url: url, params: params, tips: tips);
    if (data != null) {
      return ChangeModel.fromJson(data);
    }
    return ChangeModel();
  }
  static initContext(BuildContext context) {
    _context = context;
    // debugPrint("路由工具初始化context ===> $context");
  }
  static void loginOut() {
    // 移除登录保存的信息
    HiCache.getInstance().remove(_saveTokenKey);
    HiCache.getInstance().remove(_saveUserKey);
    // 路由跳转，跳转登录页
    Navigator.pushNamed(_context!, "/login");

  }
}
